//
//  ViewController.m
//  OpenPhotoLibrary
//
//  Created by Burn on 2019/6/17.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIWebViewDelegate>

/**相册属性*/
@property (nonatomic,strong) UIImagePickerController *pickerController;

@property(strong,nonatomic) UIImage *image;

@property(strong,nonatomic) UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.webView = [[UIWebView alloc]init];
    self.webView.frame = self.view.bounds;
    [self.view addSubview:self.webView];
    
    self.webView.delegate = self;
    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    NSString *path = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"];
    NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:html baseURL:baseURL];
    
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    
    // 创建JSContext
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    // 调用系统相机 iOSCamera 就是你自定义的一个js函数名
    /*
     举个例子
     定义一个js函数在控制台打印一句话这样写
     context[@"js函数名"] = ^(){
     NSLog(@"在控制台打印一句话");
     };
     */
    context[@"iOSCamera"] = ^(){
        
        // 调用系统相机的类
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        
        // 设置选取的照片是否可编辑
        pickerController.allowsEditing = YES;
        // 设置相册呈现的样式
        pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        // 选择完成图片或者点击取消按钮都是通过代理来操作我们所需要的逻辑过程
        pickerController.delegate = self;
        
        // 使用模态呈现相机 getCurrentViewController这个方法是用来拿到添加了这个View的控制器
//        [[self getCurrentViewController] presentViewController:pickerController animated:YES completion:nil];
        
        return @"调用相机";
    };
    
    
    context[@"iOSPhotosAlbum"] = ^(){
        
        self.pickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        self.pickerController.allowsEditing = NO;
        //打开相册
        [self presentViewController:self.pickerController animated:YES completion:nil];
        
        return @"调用相册";
        
    };
    
//    if ([self.delegate respondsToSelector:@selector(zszWebViewDidFinishLoad:)]) {
//        [self.delegate zszWebViewDidFinishLoad:webView];
//    }
}

// 图片转成base64字符串需要先取出所有空格和换行符
- (NSString *)removeSpaceAndNewline:(NSString *)str
{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}


#pragma mark - 相机相册调用
/**
 *选择完照片完成时候调用
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info

{
    //如果实现了这个代理方法 必须手动退出相册界面
    [self dismissViewControllerAnimated:YES completion:nil];
    
//    self.image = info[@"UIImagePickerControllerEditedImage"];
    
    self.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:info[@"UIImagePickerControllerImageURL"]]];
    
    //  拍照保存
    if (self.pickerController.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(info[@"UIImagePickerControllerEditedImage"], self, nil, nil);
    }
    
    NSData *imageData = UIImageJPEGRepresentation(self.image, 0.00001);
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSString *imageBase64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    imageBase64 = [self removeSpaceAndNewline:imageBase64];
    NSString *jsFunctStr = [NSString stringWithFormat:@"rtnCamera('%@')",imageBase64];
    [context evaluateScript:jsFunctStr];
}
/**
 *取消选择
 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 调用相机相册
- (void)touchUpSenderForBtn {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]){
            self.pickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            self.pickerController.allowsEditing = YES;
            //打开相册
            [self presentViewController:self.pickerController animated:YES completion:nil];
        }
    }];
    
    [alertController addAction:actionOne];
    UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            //  设置选取的照片是否可编辑
            self.pickerController.allowsEditing = YES;
            [self presentViewController:self.pickerController animated:YES completion:nil];
            
        }
        else{
            NSLog(@"打开失败");
        }
    }];
    [alertController addAction:actionTwo];
    UIAlertAction *actionThree = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:actionThree];
    [self presentViewController:alertController animated:YES completion:nil];
}



- (UIImagePickerController *)pickerController
{
    if (!_pickerController){
        _pickerController=[[UIImagePickerController alloc]init];
        _pickerController.delegate = self;
    }
    return _pickerController;
}



// 压缩图片的方法
- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.8);
}

@end
